package com.comprehensive.personalfile.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class NativeLibraryLoader {
    public static void load(String libraryName) {
        try {
            // 尝试从java.library.path加载
            System.loadLibrary(libraryName);
            System.out.println("从java.library.path加载库: " + libraryName);
            return;
        } catch (UnsatisfiedLinkError e) {
            // 忽略，尝试从资源目录加载
        }

        try {
            // 从资源目录加载
            String os = System.getProperty("os.name").toLowerCase();
            String libraryExtension;

            if (os.contains("win")) {
                libraryExtension = ".dll";
            } else if (os.contains("linux") || os.contains("mac")) {
                libraryExtension = ".so";
            } else {
                throw new UnsatisfiedLinkError("Unsupported OS: " + os);
            }

            String resourcePath = "/native/" + libraryName + libraryExtension;
            URL resourceUrl = NativeLibraryLoader.class.getResource(resourcePath);
            if (resourceUrl == null) {
                throw new UnsatisfiedLinkError("资源目录中找不到库: " + libraryName);
            }

            // 将资源文件复制到临时目录
            File tempFile = File.createTempFile(libraryName, libraryExtension);
            tempFile.deleteOnExit();

            try (InputStream inputStream = NativeLibraryLoader.class.getResourceAsStream(resourcePath);
                 FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                if (inputStream == null) {
                    throw new IOException("无法打开资源流: " + resourcePath);
                }
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            // 从临时目录加载库
            System.load(tempFile.getAbsolutePath());
            System.out.println("从资源目录加载库: " + tempFile.getAbsolutePath());
            System.out.println("成功加载本地库: " + libraryName);
        } catch (Exception ex) {
            throw new RuntimeException("加载本地库失败", ex);
        }
    }
}

